package dao

import (
	"fmt"
	"html"
	"html/template"
)

type Opt SiteOPT
type Opts []Opt

func (os Opts) GetAll() (lists Opts, err error) {
	rows, err := Db.Query("select `id`,`area_code`,`key`,`title`,`description`,`value`,`relation_id`,`short`,`extension`,`add_time`,`update_time` from bg_opt where 1")
	if err != nil {
		return
	}

	for rows.Next() {
		var (
			title       string
			description string
			data        Opt
		)

		err := rows.Scan(&data.Id, &data.AreaCode, &data.Key, &title, &description, &data.Value, &data.RelationId, &data.Short, &data.Extension, &data.AddTime, &data.UpdateTime)
		if err != nil {
			continue
		}

		data.Title = template.HTML(html.UnescapeString(title))
		data.Description = template.HTML(html.UnescapeString(description))

		lists = append(lists, data)
	}

	return
}

func (os Opts) GetAllAbout() (lists Opts, err error) {
	sql := "select `id`,`area_code`,`key`,`title`,`description`,`value`,`relation_id`,`short`,`extension`,`add_time`,`update_time` from bg_opt where area_code='about' order by short desc"
	if Db == nil {
		InitMysql()
	}

	rows, err := Db.Query(sql)
	if err != nil {
		return
	}

	for rows.Next() {
		var (
			title       string
			description string
			data        Opt
		)

		err := rows.Scan(
			&data.Id, &data.AreaCode, &data.Key, &title, &description, &data.Value, &data.RelationId, &data.Short, &data.Extension, &data.AddTime, &data.UpdateTime)
		if err != nil {
			fmt.Println(err)
			continue
		}

		data.Title = template.HTML(html.UnescapeString(title))
		data.Description = template.HTML(html.UnescapeString(description))

		lists = append(lists, data)
	}

	return
}

/**
ALL
*/
func GetFieldsAll() (datas []SiteOPT) {
	rows, err := Db.Query("select `id`,`area_code`,`key`,`title`,`description`,`value`,`relation_id`,`short`,`extension`,`add_time`,`update_time` from bg_opt where 1")
	if err != nil {
		return
	}

	for rows.Next() {
		var (
			title       string
			description string
			data        SiteOPT
		)

		err := rows.Scan(
			&data.Id, &data.AreaCode, &data.Key, &title, &description, &data.Value, &data.RelationId, &data.Short, &data.Extension, &data.AddTime, &data.UpdateTime)
		if err != nil {
			continue
		}

		data.Title = template.HTML(html.UnescapeString(title))
		data.Description = template.HTML(html.UnescapeString(description))

		datas = append(datas, data)
	}

	return
}
